package net.interest.curation;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;

import net.interest.curation.meta.FacebookUserMeta;
import net.interest.curation.meta.ScrapBookMeta;
import net.interest.curation.meta.TwitterUserMeta;
import net.interest.curation.model.FacebookUser;
import net.interest.curation.model.ScrapBook;
import net.interest.curation.model.ScrapBookEntry;
import net.interest.curation.model.SocialUser;
import net.interest.curation.model.TwitterUser;
import net.interest.curation.model.User;

import org.slim3.controller.Navigation;
import org.slim3.datastore.Datastore;

import scenic3.ScenicPage;
import scenic3.annotation.ActionPath;
import scenic3.annotation.Default;
import scenic3.annotation.Page;

import com.google.appengine.api.datastore.Key;
import com.google.gson.stream.JsonWriter;


@Page("/scrapbook")
public class ScrapBookPage  extends ScenicPage {
    private static final Logger log =
            Logger.getLogger(ScrapBookPage.class.getName());

    @ActionPath("list")
    public Navigation list() {
        User user = (User) super.request.getSession().getAttribute(User.SESSION_USER_ATTR_NAME);
        
        ScrapBookMeta meta = ScrapBookMeta.get();
        List<ScrapBook> scrapbooks = Datastore.query(meta).filter(meta.userRef.equal(user.getKey())).asList();

        super.response.setContentType("text/json");
        JsonWriter writer;
        try {
            writer = new JsonWriter(new OutputStreamWriter(super.response.getOutputStream(), "UTF-8"));
            writer.beginArray();
            for(ScrapBook book : scrapbooks){
                writer.beginObject();
                writer.name("key");
                writer.value(book.getKey().getId());
                writer.name("name");
                writer.value(book.getName());
                if(!book.getEntries().isEmpty()){
                    ScrapBookEntry entry = book.getEntries().iterator().next();
                    writer.name("service");
                    writer.value(entry.getService());
                    writer.name("content");
                    writer.value(entry.getContent());
                }

                writer.endObject();
                System.out.println(book.getName());
            }
            writer.endArray();
            writer.flush();
            writer.close();
        } catch (UnsupportedEncodingException e) {
            log.severe(e.getLocalizedMessage());
        } catch (IOException e) {
            log.severe(e.getLocalizedMessage());
       }
        return null;
    
    }
    
    @ActionPath("add")
    public Navigation add() {
        User user = (User) super.request.getSession().getAttribute(User.SESSION_USER_ATTR_NAME);
        String name = request.getParameter("name");
        
        ScrapBook scrapBook = new ScrapBook();
        scrapBook.setName(name);
        scrapBook.getUserRef().setModel(user);
        Datastore.put(scrapBook);

        super.response.setContentType("text/json");
        JsonWriter writer;
        try {
            writer = new JsonWriter(new OutputStreamWriter(super.response.getOutputStream(), "UTF-8"));
            writer.beginObject();
            writer.name("key");
            writer.value(scrapBook.getKey().getId());
            writer.name("name");
            writer.value(scrapBook.getName());
            writer.endObject();
            writer.flush();
            writer.close();
        } catch (UnsupportedEncodingException e) {
            log.severe(e.getLocalizedMessage());
        } catch (IOException e) {
            log.severe(e.getLocalizedMessage());
       }
        return null;

    }


    @ActionPath("listentry")
    public Navigation listentry() {
        String keyStr = request.getParameter("key");        
        Key key = Datastore.createKey(ScrapBookMeta.get(), Long.parseLong(keyStr));

        ScrapBook book = Datastore.get(ScrapBook.class, key);

        Collection<ScrapBookEntry> scrapbooks = book.getEntries();
        super.response.setContentType("text/json");
        JsonWriter writer;
        try {
            writer = new JsonWriter(new OutputStreamWriter(super.response.getOutputStream(), "UTF-8"));
            writer.beginArray();
            for(ScrapBookEntry entry : scrapbooks){
                writer.beginObject();
                writer.name("key");
                writer.value(entry.getKey().getId());
                writer.name("url");
                writer.value(entry.getUrl());
                writer.name("service");
                writer.value(entry.getService());
                writer.name("content");
                writer.value(entry.getContent());
                writer.endObject();
            }
            writer.endArray();
            writer.flush();
            writer.close();
        } catch (UnsupportedEncodingException e) {
            log.severe(e.getLocalizedMessage());
        } catch (IOException e) {
            log.severe(e.getLocalizedMessage());
       }
        return null;
    }

    @ActionPath("addentry")
    public Navigation addentry() {
        String keyStr = request.getParameter("key");
        String service = request.getParameter("service");
        String url = request.getParameter("url");
        String content = request.getParameter("content");
        
        Key key = Datastore.createKey(ScrapBookMeta.get(), Long.parseLong(keyStr));
        ScrapBook scrapBook = Datastore.get(ScrapBookMeta.get(), key);
        
        ScrapBookEntry entry = new ScrapBookEntry();
        entry.setService(service);
        entry.setUrl(url);
        entry.setContent(content);
        Datastore.put(entry);
        
        scrapBook.getEntrieKeys().add(entry.getKey());
        Datastore.put(scrapBook);
        return null;
    
    }

    // /
    @Default
    public Navigation index() {
        ScrapBookMeta meta = ScrapBookMeta.get();
        List<ScrapBook> scrapbooks = Datastore.query(meta).sort(meta.updatedAt.desc).asList();

        request.setAttribute("scrapbooks", scrapbooks);
        return forward("/scrapbook/index.jsp");
    }

}
